package com.example.stock.controller;

import com.example.stock.model.StockDailyData;
import com.example.stock.model.StockInfo;
import com.example.stock.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 股票信息控制器
 *
 * @author zwg
 * @date 2025/8/5 22:23
 */
@RestController
@RequestMapping("/api/stocks")
public class StockController {
    @Autowired
    private StockService stockService;

    /**
     * 获取股票基本信息
     */
    @GetMapping("/{code}")
    public ResponseEntity<StockInfo> getStockInfo(@PathVariable String code) {
        StockInfo stock = stockService.getStockInfo(code);
        return stock != null ? ResponseEntity.ok(stock) : ResponseEntity.notFound().build();
    }

    /**
     * 获取股票某日交易数据
     */
    @GetMapping("/{code}/daily")
    public ResponseEntity<StockDailyData> getStockDailyData(
            @PathVariable String code,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        StockDailyData dailyData = stockService.getStockDailyData(code, date);
        return dailyData != null ? ResponseEntity.ok(dailyData) : ResponseEntity.notFound().build();
    }

    /**
     * 获取股票历史交易数据
     */
    @GetMapping("/{code}/historical")
    public ResponseEntity<List<StockDailyData>> getStockHistoricalData(
            @PathVariable String code,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        List<StockDailyData> historicalData = stockService.getStockHistoricalData(code, startDate, endDate);
        return ResponseEntity.ok(historicalData);
    }

    /**
     * 获取市场所有股票
     */
    @GetMapping("/market/{market}")
    public ResponseEntity<List<StockInfo>> getAllStocks(@PathVariable String market) {
        List<StockInfo> stocks = stockService.getAllStocks(market);
        return ResponseEntity.ok(stocks);
    }

    /**
     * 手动触发数据更新
     */
    @PostMapping("/update")
    public ResponseEntity<String> updateStockData() {
        stockService.updateStockData();
        return ResponseEntity.ok("股票数据更新已触发");
    }
}
